package network

import (
	"sync"
	"net"
	"strconv"
)

type TcpClient struct {
	connCB     ConnectionCallBack
	exitNofity chan struct{}
	wg         sync.WaitGroup // 在退出时 让tcpServer启动的协程都被回收
}

func NewTcpClient(connCB ConnectionCallBack) *TcpClient {
	return &TcpClient{
		connCB:     connCB,
		exitNofity: make(chan struct{}),
	}
}

func (self *TcpClient) Start (ip string, port int) {
	conn, err := net.Dial("tcp", ip + ":" + strconv.Itoa(port))
	if err != nil {
		return
	}
	NewConnection(conn, self.connCB, self.exitNofity).Work(&self.wg)
}

func (self *TcpClient) Stop() {
	close(self.exitNofity)
	self.wg.Wait()
}